﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ViewTopic : System.Web.UI.Page
{

    private static int PAGESIZE = 10;//每页显示数量
    private Permission per;

    
    void fullfillLZ(Topic t)
    {
        post_LZ_title.InnerText = Server.HtmlEncode(t.title);
        if (t.m.hasAvatar == 0)
        {
            LZ_photo.Src = "./avatar/noavatar_small.gif";
        }
        else
            LZ_photo.Src = "./avatar/" + t.m.uid.ToString() + "-Small.png";
        LZ_link.HRef = "personal.aspx?uid=" + t.m.uid;
        Literal_LZ_time.Text = t.posttime.ToString();
        Literal_LZ_content.Text = ""+Server.HtmlEncode(t.text)+"";
        Literal_LZ_name.Text = t.m.nickname;
        Literal_LZ_name.NavigateUrl = "Personal.aspx?uid="+t.m.uid;
        if (per.awdel==1)
            HyperLink_delete_topic.NavigateUrl = "delete.aspx?type=topic&fid=" + t.fid + "&tid=" + t.tid;
        else
            HyperLink_delete_topic.Visible = false;

        if (per.awreply != 1)
            this.post_op_repy.Visible = false;
    }

    string GeneratePost(Reply p, int f)//生成帖子楼层
    {
        string R = "";
        string photourl ;
        if (p.auther.hasAvatar!=0)
        {
            photourl = "./avatar/" + p.auther.uid + "-small.png";
        }
        else
            photourl = "./avatar/noavatar_small.gif";

        if (p.status == 0)
        {
            p.title = "";
            p.text = "该回复已经被管理员删除！";
        }
        string userurl = "Personal.aspx?uid="+p.auther.uid;
        string post_time = p.posttime.ToString();
        string floor = f.ToString() + "楼";
        string username = p.auther.nickname;
        string title = Server.HtmlEncode(p.title);
        string content = "" + Server.HtmlEncode(p.text) + "";



        R += "<li class=\"viewtopic_content_li\" ><a class=\"post_photo\" href=\"" + userurl + "\">";
        R += "<img src=\"" + photourl + "\" /></a>";
        R += "<div class=\"post_wrap\">";
        R += "<a href=\"" + userurl + "\">" + username + "</a>";
        R += "<span class=\"post_time\">" + post_time + "</span>";
        R += "<span class=\"post_floor\">" + floor + "</span>";
        R += "<div class=\"post_content\">";
        if (title != null)
            R += "<p class=\"post_title\">" + title + "</p>";
        R += content;
        R += "</div><div class=\"post_operate\">";
        if (per.awreply == 1)
        R += "<a id=\"post_op_repy\" onclick=\"reply('" + floor + "',"+p.pid+","+p.auther.uid+");\">回复</a>";
        if(per.awdel ==1)
            R += "&nbsp;&nbsp;<a href=\"delete.aspx?type=reply&tid=" + p.tid + "&pid=" + p.pid + "&page=" + Request.QueryString["page"] + "\">删除</a>";
        R += "</div></div><div class=\"clearfloat\"></div></li>";
        return R;
    }


    Topic t;
    protected void Page_Load(object sender, EventArgs e)
    {
        CGeneral.CheckLogin(Request, Session);

        //if (Session["uid"] == null)
        //    CGeneral.GoToErrorPage(Response, "NeedLogin");

        //出错转接
        if (Request.QueryString["tid"] == null)
            CGeneral.GoToErrorPage(Response, "custom", "不存在该帖子!");
        if (Request.QueryString["page"] == null)
            CGeneral.GoToErrorPage(Response, "custom", "不存在该页面!");


        //权限管理

        per = new Permission(int.Parse(Session["gid"].ToString()));
        if(per.awaccess==0)
            CGeneral.GoToErrorPage(Response, "NeedLogin");






        //获取信息
        int tid = Check.CheckToInt(Request.QueryString["tid"]);
        if (tid == -1)
        {
            //提示 无效的帖子id
            CGeneral.GoToErrorPage(Response, "custom", "缺少参数", "无效的tid");
        }
        int page = Check.CheckToInt(Request.QueryString["page"]);
        if (page == -1)
        {
            //提示 无效的帖子id
            CGeneral.GoToErrorPage(Response, "custom", "缺少参数", "无效的页码");
        }


        //加载回复区域头像
        GetData gd = new GetData();
        if (int.Parse(Session["gid"].ToString()) == 2)
        {
            viewtopic_reply_wrap.Visible = false;
            //回复和删除不可见
        
        }
        else if (gd.GetHasAvatar(int.Parse(Session["uid"].ToString())) == 0)//没有头像
            user_photo.Src = "./avatar/noavatar_small.gif";
        else
            user_photo.Src = "./avatar/" + Session["uid"].ToString() + "-Small.png";

        t = new Topic(tid);//获取帖子
        if(t.isExist==false)
            CGeneral.GoToErrorPage(Response, "custom", "该帖子不存在");
        if(t.status==0&&per.awmag==0)//被删除帖子的权限检查
            CGeneral.GoToErrorPage(Response, "custom","YOU NEED MORE POWER");

        //回帖向对应用户发消息
        CNotice cnLZ = null;
        CNotice cnFloor = null;

        if (IsPostBack)//新回复提交后
        {
            if(Session["uid"]==null)
            {
                //提示 请登录后再回复
                CGeneral.GoToErrorPage(Response, "custom", "缺少参数", "请登录后再回复");
            }
            //判断是否回帖速度过快
            if(Session["LastPostTime"]!=null)
            {
                DateTime dt = (DateTime)(Session["LastPostTime"]);
                if(MemDisplay.IsWaterPost(dt))
                    CGeneral.GoToErrorPage(Response, "custom", "您说话太快了");
            }


            string title = viewtopic_reply_title.Text;
            string content = viewtopic_reply_form.InnerText;
            Reply p = new Reply();//构造新回复

            //录入信息
            p.tid = int.Parse(Request.QueryString["tid"].ToString());
            p.auther.uid = int.Parse(Session["uid"].ToString());
            p.auther.username = Session["username"].ToString();
            p.title = title;
            p.text = content;
            p.posttime = DateTime.Now;
            p.post_ip = Request.ServerVariables["REMOTE_ADDR"].ToString();
            p.edittime = null;
            p.edituid = null;
            p.status = 1;
            if (!Check.CheckPostLegal(p.text))
                CGeneral.GoToErrorPage(Response, "custom", "回复失败", "长度不满足要求[2,4000]");
            p.Publish();
            t.BeenReplied();//回复数+1
            if(Session["uid"]!=null)
                MemDisplay.ReplyTopic(int.Parse(Session["uid"].ToString()), DateTime.Now);//用户回复数+1
            Session["LastPostTime"] = DateTime.Now;
            
            //给楼主发送回帖提醒
            if (p.auther.uid != t.m.uid)//自己回复自己的主题不显示
            {
                cnLZ = new CNotice();
                cnLZ.fromUid = int.Parse(Session["uid"].ToString());
                cnLZ.toUid = t.m.uid;
                cnLZ.tid = t.tid;
                cnLZ.pid = -1;
                cnLZ.sendtime = DateTime.Now;
                cnLZ.isReaded = 0;
                if (p.text.Length > 10)
                    cnLZ.messageSend = p.text.Substring(0, 10) + "...";
                else
                    cnLZ.messageSend = p.text;
            }
            
            //判定是回复楼层还是直接回复主题,回复楼主的话只显示一个
            int replytoUid = int.Parse(Request.Form["uid_be_reply"].ToString());
            int replytoPid = int.Parse(Request.Form["pid_be_reply"].ToString());
            if (replytoUid != -1 && replytoPid != -1 && replytoUid!=t.m.uid)
            {
                cnFloor = new CNotice();
                cnFloor.fromUid = int.Parse(Session["uid"].ToString());
                cnFloor.toUid = replytoUid;
                cnFloor.tid = t.tid;
                cnFloor.pid = replytoPid;
                cnFloor.sendtime = DateTime.Now;
                cnFloor.isReaded = 0;
                if (p.text.Length > 10)
                    cnFloor.messageSend = p.text.Substring(0, 10) + "...";
                else
                    cnFloor.messageSend = p.text;
            }
            

            //清除值
            viewtopic_reply_title.Text = "";
            viewtopic_reply_form.InnerText = "";
            //if (t.postCount != 0)
            // Literal1.Text += GeneratePost(t.replies[t.postCount - 1],t.postCount+1);
            
            
        }
        else
        {
            if (Session["uid"] != null)
                MemDisplay.ViewTopic(int.Parse(Session["uid"].ToString()));//用户浏览数+1
             t.BeenVisited();//点击数+1
        }

        //获取帖子
        t.GetRepliesCount();//获取帖子总回复数
        int maxPage = (t.postCount + 1) / PAGESIZE;//获取最大页面
        if ((t.postCount + 1) % PAGESIZE != 0)
            maxPage++;
        if (page > maxPage)//page约束
            page = maxPage;
        if (page == 0)
            page = 1;
        //新回复重定向到尾页
        if (IsPostBack)
        {
            //向对应用户发送消息
            if (cnLZ != null)
            {

                string str1 = "";
                str1 += "ViewTopic.aspx?tid=" + t.tid + "&page=" + maxPage;
                cnLZ.address = Server.UrlEncode(str1);
                cnLZ.SendNotice();
            }
            if (cnFloor != null)
            {
                string str2 = "";
                str2 += "ViewTopic.aspx?tid=" + t.tid + "&page=" + maxPage;
                cnFloor.address = Server.UrlEncode(str2);
                cnFloor.SendNotice();
            }
            Response.Redirect("ViewTopic.aspx?tid=" + tid + "&page=" + maxPage);

        }
       
        //设置index 导航
        PageTab1.url = "ViewTopic.aspx?tid=" + tid + "&page=";
        PageTab1.num_per_page = PAGESIZE;
        PageTab1.curpage = page;
        PageTab1.topicnum = t.postCount+1;

        //显示回复
        int fn = 1;
        if (page == 1)
        {
            t.GetReplies(9, page);
            fn = 2;
        }
        else
        {
            t.GetReplies(10, page);
            fn = 1+(page - 1) * 10;
        }

        Literal1.Text = "";

        foreach (Reply r in t.replies)
        {
            Literal1.Text += GeneratePost(r, fn);//显示到网页
            fn++;
        }

        //显示楼主
        if (page == 1)
        {
            fullfillLZ(t);
        }
        else
            LZ.Visible = false;

        //初始化导航
        List<string> urls = new List<string>();
        urls.Add("Index.aspx");
        urls.Add("Forum.aspx?fid=" + t.fid + "&page=1");
        urls.Add("ViewTopic.aspx?tid=" + t.tid + "&page=1");
        navigation.urls = urls;
        List<string> names=new List<string>();
        names.Add("首页");
        names.Add(t.fName);
        names.Add(t.title);
        navigation.names = names;
    }
}